/**
 * 系统管理  设备绑定
 */
<template>
  <div style="height: 100%;width: 100%">
    <!-- 搜索筛选 -->
    <el-row :model="formInline" style="height: 5%;width: 100%;display: flex;align-items: center;">
      <el-col :span="0.5" style="margin-right: 0.5vw">
        <el-text size="large">搜索:</el-text>
      </el-col>
      <el-col :span="4" style="display: flex;align-items: center;justify-content: center;">
        <el-input size="large" v-model="formInline.userName" placeholder="请输入所属人姓名或手机号"></el-input>
      </el-col>
      <el-col :span="4" style="display: flex;">
        <el-button @click="searchDeviceByUser" size="large" style="background-color:#04c1a5;color:#fff">
          <font-awesome-icon icon="fas fa-search" />
          <span style="margin-left:1vh">查询</span>
        </el-button>
      </el-col>
      <el-col :span="4" style="display: flex;align-items: center;justify-content: center;">
        <el-input size="large" v-model="formInline.serialCode" placeholder="请输入设备序列号"></el-input>
      </el-col>
      <el-col :span="4" style="display: flex;">
        <el-button @click="searchDeviceBySerialCode" size="large" style="background-color:#04c1a5;color:#fff">
          <font-awesome-icon icon="fas fa-search" />
          <span style="margin-left:1vh">查询</span>
        </el-button>
      </el-col>
    </el-row>
    <el-row style="
    background-color: white;
    height: 35%;
    margin-top: 2vh;
    margin-bottom: 10px;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">
      <filter-list :filter-rows="rows" @updateList="updateList"/>
    </el-row>
    <!-- 分页组件5%-->
    <el-row style="display: flex;justify-content: flex-end;align-items: center;height: 5%;width: 100%;margin-bottom: 10px">
      <el-pagination
          v-model:current-page="pageParam.pageNo"
          v-model:page-size="pageParam.pageSize"
          v-model:total="pageParam.totalCount"
          :page-sizes="[1, 10, 15, 20]"
          :small="false"
          :disabled="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="100"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-row>
    <!--列表-->
    <el-table 
    
    :header-cell-style=" { background: '#F7FBFE' , color: '#000' , 'text-align': 'center' }" 
    size="large"
    :cell-style="{'text-align':'center'}"
    style="width: 100%;height: 50%"
    :data="deviceList"
    v-loading="loading" 
    highlight-current-row 
    class="customer-table" 
    border 
    element-loading-text="拼命加载中">
<!--      <el-table-column sortable prop="id" label="设备编号" width="200" >-->
<!--      </el-table-column>-->
      <el-table-column sortable prop="serialCode" label="设备序列号" width="200" >
        <template #default="scope">
          <div>{{removeSubstring(scope.row.serialCode,"ynu",false,true)}}</div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="model" label="设备型号" width="120" >
      </el-table-column>
      <el-table-column sortable prop="name" label="所属人姓名" width="130">
      </el-table-column>
      <el-table-column sortable prop="username" label="所属人手机号" width="120">
      </el-table-column>
      <el-table-column  prop="status" label="设备状态" width="100">
      </el-table-column>
      <el-table-column sortable prop="productionTime" label="生产时间" width="100">
      </el-table-column>
      <el-table-column sortable prop="activationTime" label="激活时间" width="100">
        <template v-slot="scope">
          {{ formatDateTime(scope.row.activationTime) }}
        </template>
      </el-table-column>
      <el-table-column sortable prop="expirationTime" label="到期时间" width="100">
      </el-table-column>
      <el-table-column sortable prop="expirationDate" label="使用期限" width="100">
      </el-table-column>
      <el-table-column sortable prop="processingTime" label="处理时间" width="100">
        <template v-slot="scope">
          {{ formatDateTime(scope.row.processingTime) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" min-width="100">
        <template v-slot="scope">
          <el-button size="default" type="danger" @click="showConfirmationDialog(scope.row.username,scope.row.id)">
            <font-awesome-icon icon="fa fa-trash" />
            <span style="margin-left:1vh">解除绑定</span>
            </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
        v-model="checkDialogVisible"
        title="警告"
        width="500"
        align-center
    >
      <el-text size="large">确定要解除绑定吗</el-text>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelOperation">取消</el-button>
          <el-button type="primary" style="background-color: #04c1a5;border: 0" @click="confirmOperation">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {FontAwesomeIcon} from "@fortawesome/vue-fontawesome";
import {onMounted, ref} from 'vue';

import doctor from "@/api/doctor.js";
import {ElMessage} from "element-plus";
import * as dateUtils from "@/utils/dateUtils.js";
import FilterList from "@/components/tableViews/filterList.vue";
import {removeSubstring} from "@/utils/strFormat.js";
const loading = ref(false);
const title = ref('添加');
const formInline = ref({
  userName:'',
  serialCode:''
});
const deviceList = ref([]);

//处理时间
const formatDateTime=(dateTimeString)=> {
  const date = new Date(dateTimeString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

//查询按钮
const rows = ref([
  { label: '状态', buttons: [
      // { text: '-全部-', value: null, selected: true },
      // { text: '申请绑定', value: 0, selected: false },
      { text: '已绑定', value: 1, selected: true },
      // { text: '拒绝绑定', value: 2, selected: false },
    ] },
  { label: '使用期限', buttons: [
      { text: '-全部-', value: null,selected: true },
      { text: '一个月',value: '一个月', selected: false },
      { text: '两个月', value: '两个月',selected: false },
      { text: '三个月', value: '三个月',selected: false },
      { text: '半年', value: '半年',selected: false },
      { text: '一年', value: '一年',selected: false },
      { text: '一年以上', value: '一年以上',selected: false },
    ] },
  { label: '型号', buttons: [
      { text: '-全部-', value: null,selected: true },
      { text: '睡眠呼吸监测仪',value: '睡眠呼吸监测仪', selected: false },
      { text: '慢阻肺检测仪', value: '慢阻肺检测仪',selected: false },
    ] },
  { label: '生产时间', buttons: [
      { text: '-全部-', value: null,selected: true },
      { text: '刚刚',value: 1, selected: false },
      { text: '最近1天', value: 2,selected: false },
      { text: '最近7天', value: 7,selected: false },
      { text: '最近两周', value: 14,selected: false },
      { text: '最近1个月', value: 30,selected: false },
      { text: '最近3个月', value: 90,selected: false },
      { text: '最近一年', value: 365,selected: false },
      { text: '一年以上', value: -1,selected: false },
    ] },
  { label: '激活时间', buttons: [
      { text: '-全部-', value: null,selected: true },
      { text: '刚刚',value: 1, selected: false },
      { text: '最近1天', value: 2,selected: false },
      { text: '最近7天', value: 7,selected: false },
      { text: '最近两周', value: 14,selected: false },
      { text: '最近1个月', value: 30,selected: false },
      { text: '最近3个月', value: 90,selected: false },
      { text: '最近一年', value: 365,selected: false },
      { text: '一年以上', value: -1,selected: false },
    ] },
  { label: '过期时间', buttons: [
      { text: '-全部-', value: null,selected: true },
      { text: '刚刚',value: 1, selected: false },
      { text: '最近1天', value: 2,selected: false },
      { text: '最近7天', value: 7,selected: false },
      { text: '最近两周', value: 14,selected: false },
      { text: '最近1个月', value: 30,selected: false },
      { text: '最近3个月', value: 90,selected: false },
      { text: '最近一年', value: 365,selected: false },
      { text: '一年以上', value: -1,selected: false },
    ] },
  { label: '处理时间', buttons: [
      { text: '-全部-', value: null,selected: true },
      { text: '刚刚',value: 1, selected: false },
      { text: '最近1天', value: 2,selected: false },
      { text: '最近7天', value: 7,selected: false },
      { text: '最近两周', value: 14,selected: false },
      { text: '最近1个月', value: 30,selected: false },
      { text: '最近3个月', value: 90,selected: false },
      { text: '最近一年', value: 365,selected: false },
      { text: '一年以上', value: -1,selected: false },
    ] },
]);
const updateList = (newRows) =>{
  const unBindingDeviceQuery = {
    serialCode:null,
    status:null,
    // status:1,
    currentTime:null,
    processingTimeEnd:'',
    activationTimeEnd:null,
    expirationTimeEnd:null,
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  };
  // 调用更新方法
  updateDeviceListQuery(newRows, unBindingDeviceQuery);
  requestDeviceList(unBindingDeviceQuery)
}
//分页组件
const handleCurrentChange = (newPage)=>{
  pageParam.value.pageNo = newPage;
  const unBindingDeviceQuery = {
    serialCode:null,
    status:null,
    currentTime:null,
    processingTimeEnd:'',
    applicationTimeEnd:null,
    activationTimeEnd:null,
    expirationTimeEnd:null,
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  };
  // 调用更新方法
  updateDeviceListQuery(rows.value, unBindingDeviceQuery);
  //执行查询
  requestDeviceList(unBindingDeviceQuery)
}
const handleSizeChange = ()=>{
  const deviceListQuery = {
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize,
  }
  updateDeviceListQuery(rows.value,deviceListQuery)
  requestDeviceList(deviceListQuery)
}

//列表查询
const pageParam = ref({
  pageNo:1,
  pageSize:10,
  totalCount:10,
  totalPages:10,
  nextPage:0,
  prePage:0,
  hasPre:false,
  hasNext:true,
});
onMounted(() => {
  getDevicesList();
});
const getDevicesList = ()=>{
  const deviceListQuery = {
    status: updateSelectedValue(rows.value[0].buttons),
    // status:1,
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  };
  requestDeviceList(deviceListQuery)
}
const requestDeviceList = (deviceListQuery)=>{
  loading.value = true;
  // doctor.deviceListSearch(deviceListQuery)
  doctor.bindingDeviceAuditSearch(deviceListQuery)
      .then((res) => {
        if (res.data.code === 200) {
          // 将状态码转换为中文描述
          deviceList.value = res.data.data.result
              .filter(apply => apply.status === 1)
              .map(device => ({
            ...device,
            status: getStatusText(device.status)
          }));
        }
        console.log('resunbind',res)
        updatePageParams(res.data.data)
      })
      .catch((err) => {
        console.log(err);
      }).finally(()=>{
    loading.value = false;
  });
}
function updateSelectedValue(buttons) {
  for (const button of buttons) {
    if (button.selected) {
      return button.value;
    }
  }
  return null;
}

function updateTime(buttons, currentDate) {
  for (const button of buttons) {
    if (button.selected) {
      if (button.value === -1) {
        // 对于“一年以上”按钮，设置时间为当前时间减去一年的时间
        const oneYearAgo = new Date();
        oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
        const year = oneYearAgo.getFullYear();
        const month = String(oneYearAgo.getMonth() + 1).padStart(2, '0');
        const day = String(oneYearAgo.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      } else if (button.value === null) {
        // 对于“全部”按钮，返回 null，表示不限制时间
        return null;
      } else {
        // 其他按钮，根据 value 计算时间范围
        const time = new Date();
        time.setDate(time.getDate() - button.value);
        const year = time.getFullYear();
        const month = String(time.getMonth() + 1).padStart(2, '0');
        const day = String(time.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
    }
  }
  return currentDate; // 默认取当前时间
}
function updateDeviceListQuery(rows, deviceListQuery) {
  // deviceListQuery.status = updateSelectedValue(rows[0].buttons);
  const statusButtons = rows[0].buttons;
  const selectedStatus = updateSelectedValue(statusButtons);
  // 确保 status 的值为 1
  deviceListQuery.status = selectedStatus === 1 ? selectedStatus : null;

  deviceListQuery.expirationDate = updateSelectedValue(rows[1].buttons);
  deviceListQuery.model = updateSelectedValue(rows[2].buttons);
  deviceListQuery.currentTime = dateUtils.getCurrentDate();
  deviceListQuery.productionTimeEnd = updateTime(rows[3].buttons, deviceListQuery.currentTime);
  deviceListQuery.applicationTimeEnd = updateTime(rows[4].buttons, deviceListQuery.currentTime);
  deviceListQuery.expirationTimeEnd = updateTime(rows[5].buttons, deviceListQuery.currentTime);
  deviceListQuery.processingTimeEnd = updateTime(rows[6].buttons, deviceListQuery.currentTime);

  // 如果“一年以上”按钮被选中，设置 deviceListQuery.currentTime 为当前时间减去一年的时间
  if (rows[4].buttons.find(button => button.selected && button.value === -1)) {
    deviceListQuery.currentTime = updateTime(rows[4].buttons, deviceListQuery.currentTime);
    deviceListQuery.applicationTimeEnd = "1970-01-01"; // 设置 applicationTimeEnd 为 null
  }
  if (rows[6].buttons.find(button => button.selected && button.value === -1)) {
    deviceListQuery.currentTime = updateTime(rows[6].buttons, deviceListQuery.currentTime);
    deviceListQuery.processingTimeEnd = "1970-01-01"; // 设置 applicationTimeEnd 为 null
  }
  console.log('Query Parameters:', deviceListQuery);
}


const getStatusText = (statusCode) => {
  switch (statusCode) {
    case 0:
      return "申请绑定";
    case 1:
      return "已绑定";
    case 2:
      return "拒绝绑定";
    default:
      return "未绑定";
  }
};
function updatePageParams(pageData) {
  pageParam.value.pageNo = pageData.pageNo;
  pageParam.value.pageSize = pageData.pageSize;
  pageParam.value.totalCount = pageData.totalCount;
  pageParam.value.totalPages = pageData.totalPages;
  pageParam.value.nextPage = pageData.nextPage;
  pageParam.value.hasNext = pageData.hasNext;
  pageParam.value.prePage = pageData.prePage;
  pageParam.value.hasPre = pageData.hasPre;
}

//解绑弹窗
const unbindDevice = (username,deviceId)=>{
  const unBindingDeviceEditQuery = {
    userName:username,
    deviceId:deviceId,
  }
  console.log(unBindingDeviceEditQuery)
  doctor.unBindingDeviceAudit(unBindingDeviceEditQuery).then((res)=>{
    if(res.data.code === 200){
      ElMessage.success("解绑成功")
      getDevicesList()
    }else{
      ElMessage.error(res.data.msg);
    }
  }).then((err)=>{
    console.log(err)
  })

}
const checkDialogVisible = ref(false);
const userName = ref(null);
const deviceId = ref(null);
const showConfirmationDialog = (name, did) => {
  userName.value = name;
  deviceId.value = did;
  checkDialogVisible.value = true;
};
const cancelOperation = () => {
  checkDialogVisible.value = false;
};
const confirmOperation = () => {
  checkDialogVisible.value = false;
  unbindDevice(userName.value, deviceId.value);
};

//信息查询
const searchDeviceBySerialCode = ()=>{
  const deviceListQuery = {
    serialCode: formInline.value.serialCode,
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize,
  }
  updateDeviceListQuery(rows.value,deviceListQuery)
  requestDeviceList(deviceListQuery)
}
const searchDeviceByUser= ()=>{
  const deviceListQuery = {
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize,
  }
  if (formInline.value.userName.length === 11){
    deviceListQuery.userName = formInline.value.userName
  }else{
    deviceListQuery.name = formInline.value.userName
  }
  updateDeviceListQuery(rows.value,deviceListQuery)
  requestDeviceList(deviceListQuery)
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
/* :deep(.customer-no-border-table th){
    border:none;
}
:deep(.customer-no-border-table td,.customer-no-border-table th.is-leaf)  {
  border:none;
} */
::v-deep .customer-table th{
    border:none;
  }
  ::v-deep .customer-table td,.customer-table th.is-leaf {
  border:none;
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
	/* background-color:#04c1a5; */
  background-color: green;   
    color: #fff;
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled) {
	background-color: #04c1a5;
}
/* ::v-deep {
  .el-pagination.is-background .el-pager li:not(.disabled) {
    background-color: #fff;   // 进行修改未选中背景和字体
    // color: #fff;
  }
  .el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: green;   // 进行修改选中项背景和字体
    color: #fff;
  }
} */

</style>